<script setup lang="ts">
import type { CustomDialogInstance } from '@/types'
import useMeasurePointTemplate, { generateIndicatorNumber, type AssociationIndicator }
  from '@/mixins/MixinMeasurePointTemplate'
import { unitManagementApi } from '@/api'
import { useMixinQueryIndicatorDicts } from '@/mixins/MixinQueryIndicatorDicts'

const props = defineProps<{
  energyCode: string
  code: string
  pointCode: string
  toolsId: number
  pointId: number
  energyName: string
}>()
const emits = defineEmits<{
  (e: 'saveSuccess'): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const {
  loading,
  tpls: lists,
  getTplsByEnergyCode,
  removeIndicator,
  saveTps,
  createEmptyTpl,
  removeOneError,
  addOneError,
  isInvalid,
} = useMeasurePointTemplate()
const {
  indicatorDicts,
  getIndicatorDicts,
  getKeyFromValue,
  isInternalIndicator,
} = useMixinQueryIndicatorDicts()

const [unitData, setUnitData] = useState<any[]>([])

async function getUnitData() {
  const { data: res }
    = await unitManagementApi.selectUnitList()
  setUnitData(
    res.map((item: any) => ({ id: uuid(), ...item })),
  )
}

function removeItem(row: AssociationIndicator) {
  removeIndicator(
    row._uuid_,
  )
}
function clickAdd() {
  createEmptyTpl(
    props.energyCode,
    props.pointCode,
    props.code,
  )
}

async function clickSave() {
  try {
    await saveTps(props.energyCode)
    close()
    emits('saveSuccess')
  }
  catch (e) {}
}

function handleChangeMeasuringPointNumber(val: string, row: AssociationIndicator) {
  // 指标名称是字典中定义好的时不自动生成指标编码
  if (!isInternalIndicator(row.indicatorName)) {
    row.indicatorNumber = generateIndicatorNumber(
      props.pointCode,
      props.code,
      val,
    )
  }
  if (!isInvalid(val))
    removeOneError(row._uuid_, 'measuringPointNumber')
  else
    addOneError(row._uuid_, 'measuringPointNumber')
}
function handleChangeIndicatorNumber(val: string, row: AssociationIndicator) {
  if (!isInvalid(val))
    removeOneError(row._uuid_, 'indicatorNumber')
  else
    addOneError(row._uuid_, 'indicatorNumber')
}
function handleChangeIndicatorName(val: string, row: AssociationIndicator) {
  if (!isInvalid(val))
    removeOneError(row._uuid_, 'indicatorName')
  else
    addOneError(row._uuid_, 'indicatorName')

  if (val) {
    const key = getKeyFromValue(val)
    if (key) {
      const pointCode = props.pointCode ?? ''
      row.indicatorNumber = `${pointCode}.${key}`
      row.measuringPointNumber = key

      handleChangeIndicatorNumber(row.indicatorNumber, row)
      handleChangeMeasuringPointNumber(row.measuringPointNumber, row)
    }
  }
}
function handleChangeUnitId(val: any, row: AssociationIndicator) {
  const unitList = unref(unitData)
    .map(item => item.unitList)
    .flat()
  const unit = unitList.find(
    item => item.id === val,
  )

  if (!isInvalid(val))
    removeOneError(row._uuid_, 'unitId')
  else
    addOneError(row._uuid_, 'unitId')

  if (!unit)
    return
  row.unit = unit.unitName
}
function handleChangeIndicatorMultiple(val: any, row: AssociationIndicator) {
  if (!isInvalid(val))
    removeOneError(row._uuid_, 'indicatorMultiple')
  else
    addOneError(row._uuid_, 'indicatorMultiple')
}

async function onOpen() {
  await getUnitData()
  await getIndicatorDicts()
  await getTplsByEnergyCode(
    props.energyCode,
    props.pointCode,
    props.code,
  )
}
function onClose() {
  // 关闭弹框后把其中模板的数据清除
  lists.value = []

  emits('saveSuccess')
}
function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="`管理测点模板-` + `【${energyName}】`"
    :show-footer="false" :need-saving="false"
    :no-max-height="true" width="66%"
    class="reset"
    @close="onClose"
    @open="onOpen"
  >
    <div class="mb-4 flex items-center justify-end">
      <ElButton type="primary" plain @click="clickAdd">
        新增
      </ElButton>
      <ElButton type="primary" @click="clickSave">
        保存
      </ElButton>
    </div>
    <div v-loading="loading" element-loading-custom-class="global-loading" class="h-[460px]">
      <ElTable
        id="associationModalV2Table2" :data="lists"
        height="100%"
        style="
          --el-table-header-bg-color: var(--el-bg-color-page)
        "
      >
        <template #empty>
          <TableEmpty />
        </template>
        <ElTableColumn label="测点编码" prop="measuringPointNumber" min-width="100px">
          <template #default="{ row }">
            <ElInput
              v-if="row._is_tpl_"
              :id="`id_${row._uuid_}_measuringPointNumber`" v-model.trim="row.measuringPointNumber"
              placeholder="必填项" :maxlength="15"
              class="free"
              style="
                font-family: monospace;
              "
              @input="(val: string) => handleChangeMeasuringPointNumber(val, row)"
            />
            <code v-else>{{ row.measuringPointNumber }}</code>
          </template>
        </ElTableColumn>
        <ElTableColumn v-if="false" label="指标编码" prop="indicatorNumber" min-width="150px">
          <template #default="{ row }">
            <ElInput
              v-if="row._is_tpl_"
              :id="`id_${row._uuid_}_indicatorNumber`"
              v-model.trim="row.indicatorNumber"
              placeholder="必填项" class="free"
              style="
                font-family: monospace;
              "
              @input="(val: string) => handleChangeIndicatorNumber(val, row)"
            />
            <code v-else>{{ row.indicatorNumber }}</code>
          </template>
        </ElTableColumn>
        <ElTableColumn label="指标名称" prop="indicatorName" min-width="140px">
          <template #default="{ row }">
            <IndicatorNamePicker
              v-if="row._is_tpl_"
              :id="`id_${row._uuid_}_indicatorName`"
              v-model="row.indicatorName"
              placeholder="必填项"
              :options="indicatorDicts"
              @change="(val: string) => handleChangeIndicatorName(val, row)"
            />
            <span v-else>{{ row.indicatorName }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="计量单位" prop="unitId" min-width="100px">
          <template #default="{ row }">
            <div :id="`id_${row._uuid_}_unitId`">
              <ElCascader
                v-model="row.unitId"
                :options="unitData"
                :show-all-levels="false"
                :props="{
                  label: 'unitName',
                  value: 'id',
                  children: 'unitList',
                  emitPath: false,
                }"

                placeholder="必填项"
                class="free w-full"
                @change="(val: any) => handleChangeUnitId(val, row)"
              />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn v-if="false" label="倍率" prop="indicatorMultiple" min-width="120px">
          <template #default="{ row }">
            <ElInputNumber
              :id="`id_${row._uuid_}_indicatorMultiple`" v-model="row.indicatorMultiple"
              :min="1"
              :max="100000"
              :step="1"
              step-strictly
              class="free !w-full"
              controls-position="right"
              placeholder="必填项"
              style="
                font-family: monospace;
              "
              @change="(val: any) => handleChangeIndicatorMultiple(val, row)"
            />
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="120px" fixed="right" align="center">
          <template #default="{ row }">
            <ElButton type="danger" text bg size="small" @click="() => removeItem(row)">
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
  </CustomDialog>
</template>

<style lang="scss" scoped>
:deep(.free .el-input) {
  width: 100% !important;
}
</style>
